package com.zh.system.Thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * 或许我们可以直接用线程池
 */
public class AsyncManager {

    // 创建一个固定大小的线程池
    private final ExecutorService executorService = Executors.newFixedThreadPool(4);
    private static volatile AsyncManager asyncManager;

    /**
     * 提交一个新的异步任务。
     *
     * @param task 异步任务
     */
    public void submitAsyncTask(Runnable task) {
        executorService.execute(task);
    }

    /**
     * 关闭线程池。
     */
    public void shutdown() {
        executorService.shutdown();
    }

    /**
     * 等待所有任务完成
     *
     * @param timeout
     * @param timeUnit
     * @throws InterruptedException
     */
    public void awaitAll(Long timeout, TimeUnit timeUnit) throws InterruptedException {
        executorService.awaitTermination(timeout, timeUnit);
    }
    /**
     * 保证只有一个实例
     *
     * @return AsyncManager实例
     */
    public static AsyncManager getInstance() {
        if (asyncManager == null) {
            synchronized (AsyncManager.class) {
                if (asyncManager == null) {
                    asyncManager = new AsyncManager();
                }
            }
        }
        return asyncManager;
    }
}